package fun.eliauk.shuatiba.utils;

import cn.dev33.satoken.stp.StpUtil;
import fun.eliauk.shuatiba.exception.BusinessException;
import fun.eliauk.shuatiba.manager.CounterManager;
import fun.eliauk.shuatiba.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class AntiCrawlerUtil {
    @Resource
    private CounterManager counterManager;

    @Resource
    private UserService userService;

    // 超过多少次警告
    private static final int WARN_COUNT = 10;
    // 超过多少次封号
    private static final int BAN_COUNT = 20;

    public void crawlerDetect(long useId) {
        String key = String.format("user:access:%s", useId);
        // 一分钟内访问次数，180s过期
        long count = counterManager.incrAndGetCounter(key, 1, TimeUnit.MINUTES, 180);
        if (count > BAN_COUNT) {
            // 踢下线
            StpUtil.kickout(useId);
            // 封号处理
            userService.banUser(useId);
            // 及时抛出异常，让他这一次就不能访问
            throw new RuntimeException("你是不是来爬虫的哇~~~");
        }
        if (count == WARN_COUNT) {
            // 可以改为向管理员发送邮件通知
            throw new BusinessException(110, "警告访问太频繁");
        }
    }
}

